#include "WiFi.h"
#include "aiKuaiApi/aikuaiApi.h"
#include "sysSet.h"
#include "Display/Display.h"
#include "Lvgl/Lvgl.h"
#include "LittleFS.h"
#include "webServer/webServerTask.h"

String loadCookie;
sys_set this_dev_set;
AsyncWebServer server(80);

void init_dev(void *)
{
    uint8_t i = 0;
    WiFi.begin("BYHT_2.4G", "ByHt20240418");
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        ESP_LOGD("re", "Connecting to WiFi...");
        i++;
        if (i > 15)
        {
            ESP_LOGE("WIFi", "Connecting to WiFi timeout");
            ESP.restart();
        }
    }
    loadCookie = getLoadCookie("http://yu.vip7x24.com:81/Action/login", "test", "test123");
    server.on("/login", HTTP_GET, [](AsyncWebServerRequest *request)
    {
        if (!request->authenticate("admin", "123456"))
            return request->requestAuthentication();
        request->send(200, "text/plain", "Login Success!");
    });

    server.serveStatic("/", LittleFS, "/").
            setLastModified("Mon, 26 Apr 2010 13:22:17 GMT").
            setAuthentication("admin", "123456");
    server.begin(); //启动服务器
    vTaskDelete(nullptr);
}

void setup()
{
    Serial.begin(115200);
    delay(1000);
    Serial.println("准备LittleFS ...");
    delay(1000);
    if (LittleFS.begin(true))
    {
        // 启动闪存文件系统
        ESP_LOGI("LittleFS", "剩余空间:%ld byte", LittleFS.totalBytes() - LittleFS.usedBytes());
        if (!LittleFS.exists("/system"))
        {
            LittleFS.mkdir("/system");
        }
    } else
    {
        Serial.println("LittleFS 开启失败.");
        LittleFS.format();
        ESP.restart();
    }


    xTaskCreate(init_dev,
                "init_dev",
                1024 * 20,
                nullptr,
                1,
                nullptr);

    xTaskCreate(flashDis,
                "flashDis",
                1024 * 30,
                nullptr,
                1,
                nullptr);

    xTaskCreate(LVGLLoop,
                "LVGLLoop",
                1023 * 30,
                nullptr,
                1,
                nullptr);

    delay(5000);
    ESP_LOGD("log", "getFreeHeap=%d,getFreePsram=%d,getHeapSize=%d,used=%.2f",
             ESP.getFreeHeap(),
             ESP.getFreePsram(),
             ESP.getHeapSize(),
             100-(((float)ESP.getFreeHeap() / ESP.getHeapSize()) * 100));
}


void loop()
{
}
